#!/bin/bash

echo_error() {
  echo ""
  echo -n "["
  echo -en "\\033[1;31m"
  echo -n $"ERROR "
  echo -en "\\033[0;39m"
  echo -n "]"
  echo -n " $1"
  echo -ne "\n"
  return 1
}

# 向 .bash_profile 添加环境变量
# 第1个参数：环境变量的名字。如果只有这一个参数，则视为设置了一段注释文字
# 第2个参数：环境变量的值。如果值为 HRSCOMMENT ，则把第一个参数作为注释加入
# 第3个参数：用户名。没传入则使用当前用户的$HOME获得主目录
# 如果传入参数中有空格，需要用\把每个空格都转义
  if [ $# -ne 3 ]; then
    echo "missing args";
    while [ $# -gt 0 ]; do
      echo "arg=$1"
      shift
    done
    exit 1;
  fi

  USER_HOME_DIR=`grep "^${3}:" /etc/passwd | cut -d : -f 6` || { echo_error "get ${3} USER_HOME_DIR fail"; exit 1; }
  if [ "x${USER_HOME_DIR}" = "x" ]; then echo_error "user [${3}]'s HOME dir not exist"; exit 1; fi

  # 第2个参数为"HRSCOMMENT"，意味着设置注释信息
  if [ "$2" = "HRSCOMMENT" ]; then
    tmp_value=`grep "^#[[:space:]]*${1}" $USER_HOME_DIR/.bash_profile`
    if [ -z "$tmp_value" ]; then
      echo "" >> $USER_HOME_DIR/.bash_profile
      echo "# ${1}" >> $USER_HOME_DIR/.bash_profile
    fi
    exit 0
  fi

  # 设置环境变量
  sed -i "/^[[:space:]]*${1}=.*/d" $USER_HOME_DIR/.bash_profile || { echo_error "set profile [${1}] fail"; exit 1; }
  echo "${1}=${2}" >> $USER_HOME_DIR/.bash_profile
  # 复查
  tmp_new_value=`grep "^[[:space:]]*${1}=.*" $USER_HOME_DIR/.bash_profile | sed -e 's/.*=//'`
  if [ "x$tmp_new_value" != "x${2}" ]; then
    echo_error "set [${1}=${2}] fail, because new_value is [${tmp_new_value}]."
    exit 1
  fi
